package mapmaker.robot.sensors;

import java.util.ArrayList;
import java.util.concurrent.Semaphore;

import mapmaker.network.NetworkCommunication;
import mapmaker.pose.Pose;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


public class Lasers {

	private LasersProperties properties;
	private ArrayList<Double> lasersEchoes;
	private ArrayList<Double> lasersOverflow;
	private ArrayList<Double> lasersReflector;
	public static Semaphore LASERS_SEM = new Semaphore(1, true);

	public Lasers(ArrayList<Double> lasers) {
		this.lasersEchoes = lasers;
	}

	public Lasers(){
		lasersEchoes = new ArrayList<Double>();
		lasersOverflow = new ArrayList<Double>();
		lasersReflector = new ArrayList<Double>();
		getCurrentLasersProperties();
		getCurrentLasers();
	}

	public ArrayList<Double> getLasersEchoes() {
		return lasersEchoes;
	}

	public void setLasersEchoes(ArrayList<Double> lasers) {
		this.lasersEchoes = lasers;
	}

	public void setLaserPropertiesFromJSON(JSONObject obj){ 
		Pose p = new Pose();
		p.setPoseFromJSONObject(obj);
		properties = new LasersProperties(obj.getDouble("AngleIncrement"), obj.getDouble("EndAngle"), obj.getDouble("StartAngle"), p);
	}

	/**
	 * Set laser echors from JSON object previously retrieved from server
	 * @param obj
	 */
	@SuppressWarnings("unchecked")
	public void setLasersEchoesFromJSON(JSONObject obj){
		lasersEchoes.clear();
		JSONArray array = obj.getJSONArray("Echoes");
		for(int i = 0; i < array.size(); i++){
			lasersEchoes.add(array.getDouble(i));
		}
		lasersOverflow.clear();
		lasersOverflow.addAll(obj.getJSONArray("Overflow"));
		lasersReflector.clear();
		lasersReflector.addAll(obj.getJSONArray("Reflector"));
	}

	/**
	 * Set the lasers echoes from the server after getting it by an HTTP request 
	 */
	public void getCurrentLasers(){
		JSONObject json = NetworkCommunication.getRobotLaserEchoesFromServer();
		setLasersEchoesFromJSON(json);
	}

	/**
	 * Set the lasers properties from the server after getting it by an HTTP request 
	 */
	public void getCurrentLasersProperties(){
		JSONObject json = NetworkCommunication.getRobotLaserPropertiesFromServer();
		setLaserPropertiesFromJSON(json);
	}

	/**
	 * Get the index in the echoes array of the laser corresponding to the parameter angle
	 * @param angle
	 * @return
	 */
	public int getIndexLaserOfAngle(double angle){
		return (int) Math.abs((angle - properties.getStartAngle()) / properties.getAngleIncrement());
	}

	public LasersProperties getLasersProperties(){
		return properties;
	}
}
